package com.hyper_yang.algorithmRecord;

import java.util.HashSet;
import java.util.Set;

// 最长连续序列
public class LeetCode_128 {
    /*
        给定一个未排序的整数数组 nums ，找出数字连续的最长序列（不要求序列元素在原数组中连续）的长度。
     */
    // 方法一: 暴力法
    public static int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int i : nums) {
            set.add(i);
        }
        int maxLen = 0;
        // 每个数字都作为起始点，试一下
        for (int num : set) {
            // 确保是起点 (稍微优化)
            if (!set.contains(num - 1)) {
                int currNum = num;
                int currLen = 1;
                while (set.contains(currNum + 1)) {
                    currLen++;
                    currNum++;
                }
                maxLen = Math.max(maxLen, currLen);
            }
        }
        return maxLen;
    }

    public static void main(String[] args) {
        System.out.println(longestConsecutive(new int[]{100, 4, 200, 1, 3, 2})); // 4
        System.out.println(longestConsecutive(new int[]{0, 3, 7, 2, 5, 8, 4, 6, 0, 1})); // 9
        System.out.println(longestConsecutive(new int[]{1, 0, 1, 2})); // 3
    }
}
